package com.example.demo.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fu
 * @date 2022/10/20
 */
@RestController
@RequestMapping("/api")

public class pdfController {

    @GetMapping("/getPdf")
    public String goetPdf(HttpServletResponse response) throws FileNotFoundException {
        String path = generatePdf();
        downloadNet(path, response);
        return "ok";
    }


    public void downloadNet(String path, HttpServletResponse response) {
        InputStream fis = null;
        OutputStream out = null;
        // path是指欲下载的文件的路径。
        File file = new File(path);
        // 取得文件名。
        String fileName = file.getName();
        System.out.println(fileName);
        try {
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            // 清空response
            response.reset();
            out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            //如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            out.write(buffer);
            out.flush();

        } catch (IOException ex) {
            ex.getStackTrace();
        } finally {
            try {
                File f = new File(path);
                f.delete();
                if (fis != null) {
                    fis.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public String generatePdf() {
        File path = new File(System.getProperty("java.io.tmpdir") + File.separator + "pdf");
        if (path.mkdirs()) ;
        // pdf模板地址
        String templatePath = new ClassPathResource("templates/8.pdf").getPath();
        // 生成后pdf文件的地址

        String outPdfPath = path + File.separator + "现场采样记录.pdf";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            //输出流
            out = new FileOutputStream(outPdfPath);
            //读取pdf模板
            reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);

            // 获得pdf模板中的文字域
            AcroFields form = stamper.getAcroFields();

            // 设置文字样式
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            ArrayList<BaseFont> fonts = new ArrayList<>();
            fonts.add(baseFont);
            form.setSubstitutionFonts(fonts);
            // 设置填充的文字内容
            Map<String, String> map = new HashMap<>();
            map.put("Text1", "0");
            map.put("Text2", "2");
            map.put("Text3", "6");
            map.put("Text4", "6");
            // 填充pdf模板中的文本域
            for (Map.Entry<String, String> entry : map.entrySet()) {
                form.setField(entry.getKey(), entry.getValue());
            }
            // 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
            stamper.setFormFlattening(true);
            stamper.close();
            //创建空的文档，并将生产的pdf复制到文档中
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = null;
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
                System.out.println();
            }
            // 关闭文档
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outPdfPath;
    }

}
